<?php
/***********************************************************************
 * @package    IvanEngine
 * @subpackage Core
 * @author     Ivan <ivanzx@msn.com>
 * @created    2010-05-23
 ***********************************************************************/
if(defined("IVANENGINE_CORE_MVC_CONTROLLER"))
	die("Redefinition macro in :".__FILE__."(".__LINE__.")");
define("IVANENGINE_CORE_MVC_CONTROLLER", true);

require_once (dirname(__FILE__).'/../Common.php');

class CController extends CObject 
{
    protected
        $m_context      = null;
	public function __construct()
	{
		parent::__construct();
        $this->Initialize();
	}

	public function __destruct()
	{
		parent::__destruct();
	}
	
	public function Initialize()
    {
        $this->m_context    = CContext::Get();
    }
    
    public function Forward($pluginName, $actionName = 'Index')
    {
        // new page
        if( empty($pluginName) )
        {
            $plugin = CPluginManager::Get()->LoadPlugin(CPluginManager::HOMEPAGE_NAME);
            if( $plugin == null ){
                throw new CException404Error('You must make sure "'.
                    CPluginManager::HOMEPAGE_NAME.'" plugin exsit.');
            }
            
            $plugin->ExecuteAction('Requisite', $this->m_context->GetRequest());
            return;
        }
        
        // new request
        if( $actionName == null ){
            throw new CException404Error('Can not processed the request, beacuse lost action parameter' );
        }
        
        $pluginName = preg_replace('/[^a-z0-9_]+/i', '', $pluginName);
        $actionName = preg_replace('/[^a-z0-9_]+/i', '', $actionName);
        $plugin     = CPluginManager::Get()->LoadPlugin($pluginName);
        
        if( $plugin == null ){
            throw new CException404Error('Can not processed the request, beacuse can not find the plugin: '.$pluginName );
        }
        
        $plugin->ExecuteAction($actionName, $this->m_context->GetRequest());
    }
    
    protected function ActionExists($pluginName, $actionName)
    {
        $result = CPluginManager::Get()->PluginExists($pluginName);
        if( !$result )return $result;
        $ActionClassName    = CPluginManager::GetActionClassName($pluginName);
        $ActionName         = CPlugin::GetActionName($actionName);
        if( !in_array($ActionName, get_class_methods($ActionClassName)) ){
            throw new CException(sprintf('Can not found the function: %s::%s', $ActionClassName, $ActionName));
        }
        return true;
    }
}
?>